<?php

namespace app\meizhuangapi\controller\user;

use app\meizhuangapi\controller\Controller;
use app\meizhuangapi\model\Express as ExpressModel;
use app\meizhuangapi\model\OrderGoods as OrderGoodsModel;
use app\meizhuangapi\model\OrderRefund as OrderRefundModel;
use app\meizhuangapi\model\UserAddress;
use app\meizhuangapi\model\Order as OrderModel;
use think\Db;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use app\api\controller\user\Refund as RefundModel;
/**
 * 订单售后服务
 * Class service
 * @package app\api\controller\user\order
 */
class Refund extends RefundModel
{
    /*
    * 退款原因
    */
    public function refundReason(){
        $refundinfo=['不想要了','货物有破损','生产日期与描述不符','少件/漏发','重复购买','其他'];
        $changeinfo=['太小了','太大了','规格选错了','其他'];
        $flag=input('post.flag');
        if($flag==1){
            return $this->renderSuccess($refundinfo,'获取成功');
        }else{
            return $this->renderSuccess($changeinfo,'获取成功');
        }

    }
    /**
     * 用户售后单列表
     */
    public function lists($state = -1){
        $model = new OrderRefundModel;
        $wxapp_id=input('post.wxapp_id');
        $list = $model->getList($this->user['user_id'], (int)$state);
        //var_dump($list->toArray());die;
        $list=$list->toArray();
        $storeInfo=Db::name('store_shop')->where(['wxapp_id'=>$wxapp_id])->field('shop_name,logo_image_id')->find();
        if($list['data']){
            foreach($list['data'] as $k=>$v){
                //获取商家信息
                //获取头像，资质图片
                $tx=Db::name('upload_file')->where(['file_id'=>$storeInfo['logo_image_id']])->find();
                //$zz=Db::name('upload_file')->where(['file_id'=>$storeInfo['image_id_yyzz']])->find();
                $storeInfo['headImageUrl']=$tx['file_url'].'/'.$tx['file_name'];
                $list['data'][$k]['storeInfo']=$storeInfo;

                $money=Db::name('order_goods')->where(['order_goods_id'=>$v['order_goods_id']])->field('total_pay_price')->find();
                $list['data'][$k]['money']=$money['total_pay_price'];
                //判断是否显示填写发货单
                if($v['type']['value']==30){
                    //仅退款
                    $list['data'][$k]['isShowButton']='false';
                }else{
                    if(empty($v['express_no'])){
                        $list['data'][$k]['isShowButton']='true';
                    }else{
                        $list['data'][$k]['isShowButton']='false';
                    }
                }
            }
        }
        return $this->renderSuccess(compact('list'));
    }
    /*
     * 删除售后记录
     */
    public function deleOrderRefund(){
        $order_refund_id=input('post.order_refund_id');
        $info=Db::name('order_refund')->where(['order_refund_id'=>$order_refund_id])->find();
        if($info){
            if($info['status']==0){
                return $this->renderError('进行中的售后订单不能删除');
            }else{
                Db::name('order_refund')->where(['order_refund_id'=>$order_refund_id])->delete();
                return $this->renderSuccess('删除成功');
            }
        }
        return $this->renderError('未查询到售后信息');
    }
    /*
     * 取消售后
     */
    public function cancelOrderRefund(){
        $order_refund_id=input('post.order_refund_id');
        $info=Db::name('order_refund')->where(['order_refund_id'=>$order_refund_id])->find();
        if($info){
            if($info['status']==0&&$info['is_agree']==0){
                Db::name('order_refund')->where(['order_refund_id'=>$order_refund_id])->update(['status'=>30,'cancel_time'=>time()]);
                return $this->renderSuccess('取消成功');
            }else{
                return $this->renderError('该售后订单不能取消');
            }
        }
        return $this->renderError('未查询到售后信息');
    }
    /*
     * 选择服务
     */
    public function getService(){
        $order_id=input('post.order_id');
        $order_goods_id=input('post.order_goods_id');//订单记录表id
        $model = OrderModel::getUserOrderDetail($order_id, $this->user['user_id']);
        //该订单是否允许申请售后
        $model['isAllowRefund'] = $model->isAllowRefund();
        if(!$model['isAllowRefund']){
            return $this->renderError('该订单不允许售后');
        }
        $goods=OrderGoodsModel::detail($order_goods_id);
        //售后类型(10退货退款 20换货 30 只退款不退货
        //var_dump($model['receipt_status']);
        if($model['receipt_status']['value']==20||$model['order_status']['value']==30){
            $type=['10','20','30'];
        }else{
            $type=['10','30'];
        }

        return $this->renderSuccess([
            'orderGoodsInfo' => $goods,
            'type'=>$type,
            'apiRemark'=>'注释：售后类型(type:10 退货退款 20 换货 30 只退款不退货)'
        ]);
    }
    /**
     * 申请售后
     */
    public function apply(){
        $order_goods_id=input('post.order_goods_id');//订单记录表id
        $assign_type=input('post.assign_type');//数据返回逻辑类型
        //订单商品详情
        $goods=OrderGoodsModel::detail($order_goods_id);
        if(isset($goods['refund'])&&!empty($goods['refund'])&&$goods['refund']['status']['value']!=30&&$goods['refund']['status']['value']!=10){
            return $this->renderError('当前商品已申请售后');
        }
        if($assign_type==1){
            //返回用户默认收货地址
            $address=$this->user['address_id'];
            $detail = UserAddress::detail($this->user['user_id'], $address);
            $region = array_values($detail['region']);
            $goods['addressInfo']=$detail;
            $goods['region']=$region;
            return $this->renderSuccess(['detail' => $goods],'获取成功');
        }
        $imagesId=input('post.imagesId');//售后图片id字符串
        $type=input('post.type');//10退货退款 20换货 30 只退款不退货
        $content=input('post.content');//退款/换货 描述
        $YuanYin=input('post.YuanYin');//退款/换货 原因
        $addressId=input('post.addressId');//要收货的地址id
        $goodStatus=input('post.goodStatus');//申请售后时商品状态
        $orderRefundId=input('post.order_refund_id');
        //根据退货方式组合提交的数据  (10退货退款 20换货 30 只退款不退货)
        if($type==10){
            //退货退款
            $data=[
                'content'=>$content,
                'type'=>$type,
                'apply_desc'=>$YuanYin,
                'apply_order_status'=>$goodStatus,
                'imagesId'=>$imagesId,
                'order_goods_id'=>$order_goods_id,
            ];
        }elseif($type==20){
            //换货
            $data=[
                'content'=>$content,
                'type'=>$type,
                'apply_desc'=>$YuanYin,
                'imagesId'=>$imagesId,
                'order_goods_id'=>$order_goods_id,
                'addressId'=>$addressId,
            ];
        }else{
            //只退款不退货
            $data=[
                'content'=>$content,
                'type'=>$type,
                'apply_desc'=>$YuanYin,
                'apply_order_status'=>$goodStatus,
                'imagesId'=>$imagesId,
                'order_goods_id'=>$order_goods_id,
            ];
        }
        //新增售后单记录
        $model=new OrderRefundModel;
        if ($model->apply($this->user,$goods,$data,$orderRefundId)) {
            return $this->renderSuccess([],'提交成功');
        }
        return $this->renderError($model->getError() ?: '提交失败');
    }
    /*
     * 售后图片上传
     */
    public function uploadImage(){
        $file=request()->file('image');
        $wxapp_id=input('post.wxapp_id');//小程序id
        //获取七牛配置信息
        $config=Db::name('base_setting')->where(['key'=>'storage'])->find();
        $configArray=json_decode($config['values'],'true');
        $def=$configArray['default'];
        $accessKey=$configArray['engine'][$def]['access_key'];
        $secretKey=$configArray['engine'][$def]['secret_key'];
        //构建鉴权对象
        $auth=new Auth($accessKey, $secretKey);
        //要上传的空间,这是在你七牛后台设置的
        $bucket=$configArray['engine'][$def]['bucket'];
        //生成上传 Token
        $token=$auth->uploadToken($bucket);
        //要上传文件的本地路径
        $filePath=$file->getRealPath();
        //上传到七牛后保存的文件名
        $ext = pathinfo($file->getInfo('name'),PATHINFO_EXTENSION);
        $key = substr(md5($file->getRealPath()),0,5).date('YmdHis').rand(0,9999).'.'.$ext;
        $uploadMgr=new UploadManager();
        list($res,$err)=$uploadMgr->putFile($token, $key, $filePath);
        if($err!==null){
            return json(['msg'=>'上传失败','code'=>'error','data'=>[]]);
        }else{
            //将上传记录售后记录表
            $data['storage']='qiniu';
            $data['group_id']=0;
            $data['file_name']=$res['key'];
            $data['file_size']=$file->getSize();
            $data['file_type']='image';
            $data['extension']=$ext;
            $data['is_user']=0;
            $data['wxapp_id']=$wxapp_id;
            $data['is_recycle']=0;
            $data['is_delete']=0;
            $data['create_time']=time();
            $data['file_url']=$configArray['engine'][$def]['domain'];
            $res1=Db::name('upload_file')->insertGetId($data);
            if($res1){
                //返回文件id和访问地址
                $return['imageUrl']=$configArray['engine'][$def]['domain'].'/'.$res['key'];
                $return['file_id']=$res1;
                return json(['msg'=>'上传成功','code'=>'success','data'=>$return,'apiRemark'=>'提交时将多个file_id拼接字符串']);
            }
            return json(['msg'=>'上传成功','code'=>'success','data'=>$res]);
        }
    }
    /**
     * 售后单详情
     */
    public function detail(){
        $order_refund_id=input('post.order_refund_id');
        $wxapp_id=input('post.wxapp_id');
        //售后单详情
        $detail=OrderRefundModel::detail([
            'user_id' => $this->user['user_id'],
            'order_refund_id' => $order_refund_id
        ]);
        if(empty($detail)){
            return $this->renderError('售后单信息不存在');
        }
        //获取回寄信息
        $addressInfo=Db::name('store_shop')->where(['wxapp_id'=>$wxapp_id])->find();
        //获取省市区信息
        $sheng=Db::name('region')->where(['id'=>['in',[$addressInfo['province_id'],$addressInfo['city_id'],$addressInfo['region_id']]]])->select();
        $ssq='';
        foreach ($sheng as $k=>$v){
            $ssq.=$v['name'];
        }
        $addressInfo['ssq']=$ssq;
        //物流公司列表
        $expressList = ExpressModel::getAll();
        return $this->renderSuccess(compact('detail', 'expressList','addressInfo'));
    }

    /**
     * 用户发货
     */
    public function delivery(){
        $order_refund_id=input('post.order_refund_id');
        //售后单详情
        $model=OrderRefundModel::detail([
            'user_id' => $this->user['user_id'],
            'order_refund_id' => $order_refund_id
        ]);
        if ($model->delivery($this->postData())) {
            return $this->renderSuccess([], '操作成功');
        }
        return $this->renderError($model->getError() ?: '提交失败');
    }
    /*
     * 退款进度
     */
    public function getOrderRefundStatus(){
        $order_refund_id=input('post.order_refund_id');//售后订单id
        $info=Db::name('order_refund')->where(['order_refund_id'=>$order_refund_id])->find();
        if(empty($info)){
            return $this->renderError('售后单信息不存在');
        }
        //获取订单号
        $orderNo=Db::name('order')->where(['order_id'=>$info['order_id']])->field('order_no')->find();
        //获取退款金额
        $money=Db::name('order_goods')->where(['order_goods_id'=>$info['order_goods_id']])->field('total_pay_price')->find();
        $info['order_no']=$orderNo['order_no'];
        $info['money']=$money['total_pay_price'];
        if($info['type']==10){
            $msg='退货退款';
        }elseif ($info['type']==20){
            $msg='换货';
        }else{{
            $msg='仅退款';
        }}
        $info['applyMessage']='您的'.$msg.'信息已提交';
        $info['cancelMessage']='';//取消时间
        $info['checkMessage']='';//商家审核时间
        $info['sendMessage']='';//用户发货时间
        $info['receiptMessage']='';//商家收货时间
        if(!empty($info['check_time'])&&$info['is_agree']!=0){
            //商家同意了你的申请，商家拒绝了你的申请
            if($info['is_agree']==10){
                $info['checkMessage']='商家同意了你的申请';
            }
            if($info['is_agree']==20){
                $info['checkMessage']='商家拒绝了你的申请';
            }
        }
        if(!empty($info['cancel_time'])&&$info['status']==30){
            $info['cancelMessage']='您取消了申请';
        }
        if(!empty($info['send_time'])){
            $info['sendMessage']='您已发货至商家';
        }
        if(!empty($info['receipt_time'])&&$info['is_receipt']==1){
            $info['receiptMessage']='商家已收到货';
        }
        $apply=[
            'time'=>date('Y-m-d h:i:s',$info['create_time']),
            'message'=>$info['applyMessage']
        ];
        $cancel=[
            'time'=>date('Y-m-d h:i:s',$info['cancel_time']),
            'message'=>$info['cancelMessage']
        ];
        $check=[
            'time'=>date('Y-m-d h:i:s',$info['check_time']),
            'message'=>$info['checkMessage']
        ];
        $send=[
            'time'=>date('Y-m-d h:i:s',$info['send_time']),
            'message'=>$info['sendMessage']
        ];
        $receipt=[
            'time'=>date('Y-m-d h:i:s',$info['receipt_time']),
            'message'=>$info['receiptMessage']
        ];
        $message=[$apply,$cancel,$check,$send,$receipt];
        $info['message']=[];
        foreach($message as $k=>$v){
            if(!empty($v['message'])){
                $info['message'][]=$v;
            }
        }
        return $this->renderSuccess($info,'获取成功');
    }
}